import CryptoJS from 'crypto-js'

const KP = {
  key: '1234567812345678', // 秘钥 16*n:
  iv: '1234567812345678' // 偏移量
}

// 加密
function getAesString(data: string, key: string, iv: string) {
  const _key = CryptoJS.enc.Utf8.parse(key)
  const _iv = CryptoJS.enc.Utf8.parse(iv)

  const encrypted = CryptoJS.AES.encrypt(data, _key, {
    iv: _iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })

  return encrypted.toString()
}

// 解密
function getDAesString(encrypted: string, key: string, iv: string) {
  const _key = CryptoJS.enc.Utf8.parse(key)
  const _iv = CryptoJS.enc.Utf8.parse(iv)
  const decrypted = CryptoJS.AES.decrypt(encrypted, _key, {
    iv: _iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

// AES 对称秘钥加密
export const aes = {
  en: (data: any) => getAesString(data, KP.key, KP.iv),
  de: (data: any) => getDAesString(data, KP.key, KP.iv)
}
